<template>
  <div class="mind-map-container">
    <div ref="mindMapContainer" class="mind-map-canvas"></div>

    <!-- 右键菜单 -->
    <div
      ref="contextMenu"
      class="context-menu"
      v-show="contextMenuVisible"
      :style="contextMenuStyle"
      @click.stop
    >
      <div class="context-menu-item" @click="insertSiblingNode">
        <span class="menu-icon">⊞</span>
        <span class="menu-text">插入同级节点</span>
      </div>
      <div class="context-menu-item" @click="insertChildNode">
        <span class="menu-icon">└</span>
        <span class="menu-text">插入子级节点</span>
      </div>
      <div class="context-menu-item" @click="insertParentNode">
        <span class="menu-icon">┌</span>
        <span class="menu-text">插入父级节点</span>
      </div>
      <div class="context-menu-divider"></div>
      <div class="context-menu-item danger" @click="deleteNodeWithChildren">
        <span class="menu-icon">🗑</span>
        <span class="menu-text">删除节点</span>
      </div>
      <div class="context-menu-item danger" @click="deleteCurrentNodeOnly">
        <span class="menu-icon">✂</span>
        <span class="menu-text">仅删除当前节点</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  defineProps,
  defineEmits,
  nextTick,
  defineExpose,
} from "vue";
import MindMap from "simple-mind-map";

// Props定义
const props = defineProps({
  // 思维导图数据
  mindMapData: {
    type: Object,
    required: true,
  },
  // 主题配置
  themeConfig: {
    type: Object,
    default: () => ({}),
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
});

// Emit事件定义
const emit = defineEmits([
  "node-context-menu-action", // 右键菜单操作事件
]);

// 响应式数据
const mindMapContainer = ref(null);
const mindMapInstance = ref(null);
const highlightedNodes = ref(new Set());

// 右键菜单相关数据
const contextMenu = ref(null);
const contextMenuVisible = ref(false);
const contextMenuStyle = ref({});
const currentRightClickNode = ref(null);

// 性能优化：节点缓存
const nodeCache = ref({
  allNodes: [],
  nodeMap: new Map(), // id -> node
  nameMap: new Map(), // name -> [nodes]
  typeMap: new Map(), // type -> [nodes]
});

// 内部数据副本，用于动态修改
const internalMindMapData = ref({
  nodes: [],
  links: [],
});

// 初始化思维导图
const _initMindMap = async (mindMapData) => {
  if (!mindMapContainer.value) return;

  // 检查数据是否存在
  if (!mindMapData || !mindMapData.nodes || !mindMapData.links) {
    console.warn("等待mindMapData数据...");
    return;
  }

  try {
    // 转换数据
    const convertedData = _convertToMindMapData(mindMapData);

    if (!convertedData) {
      console.error("数据转换失败");
      return;
    }

    // 默认主题配置
    const defaultThemeConfig = {
      root: {
        shape: "rectangle",
        fillColor: "#4A90E2",
        borderColor: "#4A90E2",
        borderWidth: 2,
        color: "#ffffff",
        fontSize: 16,
        fontWeight: 600,
        paddingX: 20,
        paddingY: 12,
        borderRadius: 8,
      },
      second: {
        shape: "rectangle",
        fillColor: "#7ED321",
        borderColor: "#7ED321",
        borderWidth: 2,
        color: "#ffffff",
        fontSize: 14,
        fontWeight: 500,
        paddingX: 16,
        paddingY: 10,
        borderRadius: 6,
      },
      node: {
        shape: "rectangle",
        fillColor: "#F5A623",
        borderColor: "#F5A623",
        borderWidth: 1,
        color: "#ffffff",
        fontSize: 12,
        fontWeight: 400,
        paddingX: 12,
        paddingY: 8,
        borderRadius: 4,
      },
      line: {
        width: 2,
        color: "#4A90E2",
        activeWidth: 3,
        activeColor: "#2E7BD4",
      },
    };

    // 深度合并主题配置
    const mergeThemeConfig = (defaultConfig, customConfig) => {
      const merged = { ...defaultConfig };

      for (const key in customConfig) {
        if (Object.prototype.hasOwnProperty.call(customConfig, key)) {
          if (
            typeof customConfig[key] === "object" &&
            customConfig[key] !== null &&
            typeof defaultConfig[key] === "object" &&
            defaultConfig[key] !== null
          ) {
            // 深度合并对象
            merged[key] = { ...defaultConfig[key], ...customConfig[key] };
          } else {
            // 直接赋值
            merged[key] = customConfig[key];
          }
        }
      }

      return merged;
    };

    const finalThemeConfig = mergeThemeConfig(
      defaultThemeConfig,
      props.themeConfig
    );
    // 创建思维导图实例
    mindMapInstance.value = new MindMap({
      el: mindMapContainer.value,
      data: convertedData,
      themeConfig: finalThemeConfig,
      openPerformance: true,
      // 编辑模式配置
      readonly: !props.isEdit,
      // 禁用双击编辑节点文本
      enableNodeTextEditOnDoubleClick: false,
    });

    // 绑定事件
    _bindMindMapEvents();

    // 添加全局点击事件监听器，用于隐藏右键菜单
    _addGlobalEventListeners();

    // 彻底禁用键盘快捷键
    _disableAllKeyboardShortcuts();

    // 彻底禁用节点编辑功能
    _disableNodeEditing();

    // 初始化完成后居中显示
    setTimeout(() => {
      if (mindMapInstance.value) {
        mindMapInstance.value.view.fit();
      }
    }, 100);
  } catch (error) {
    console.error("思维导图初始化失败:", error);
  }
};

// 绑定思维导图事件
const _bindMindMapEvents = () => {
  if (!mindMapInstance.value) return;

  // 用于防止事件冒泡的标记
  let isNodeClicked = false;

  // 节点的单击事件
  mindMapInstance.value.on("node_click", (node) => {
    isNodeClicked = true;

    if (node?.uid) {
      highlightNodeAndChildrenByNodeId(node.uid);
    }

    // 重置标记，延迟一点确保其他事件处理完成
    setTimeout(() => {
      isNodeClicked = false;
    }, 10);
  });

  // 节点的双击事件
  mindMapInstance.value.on("node_dblclick", (node, e) => {
    console.log("节点的双击事件:", node);
    isNodeClicked = true;

    // 阻止默认的双击编辑行为
    if (e && typeof e.preventDefault === 'function') {
      e.preventDefault();
      e.stopPropagation();
    }

    // 确保不进入编辑模式
    if (mindMapInstance.value && mindMapInstance.value.renderer) {
      // 取消任何可能的文本编辑状态
      mindMapInstance.value.renderer.textEdit?.hideEditTextBox();
    }

    console.log("双击编辑已被禁用");

    // 重置标记
    setTimeout(() => {
      isNodeClicked = false;
    }, 10);
  });

  // 节点的右键事件
  mindMapInstance.value.on("node_contextmenu", (e, node) => {
    e.preventDefault(); // 阻止默认右键菜单
    e.stopPropagation(); // 阻止事件冒泡

    // 获取鼠标位置
    const { clientX: x, clientY: y } = e;

    // 显示自定义右键菜单
    showContextMenu(x, y, node);
  });

  // 渲染树数据变化，可以监听该方法获取最新数据
  mindMapInstance.value.on("data_change", (data) => {
    console.log("渲染树数据变化:", data);
  });

  // 节点文本编辑框显示事件 - 强制禁用编辑
  mindMapInstance.value.on("show_text_edit", (node, textEditElement) => {
    console.log("检测到文本编辑尝试，已被禁用", node);

    // 立即隐藏编辑框
    if (mindMapInstance.value && mindMapInstance.value.renderer && mindMapInstance.value.renderer.textEdit) {
      // 使用setTimeout确保在下一个事件循环中执行，避免时序问题
      setTimeout(() => {
        mindMapInstance.value.renderer.textEdit.hideEditTextBox();
      }, 0);
    }

    // 如果有传入的编辑元素，直接隐藏
    if (textEditElement && textEditElement.style) {
      textEditElement.style.display = 'none';
    }
  });

  // 节点文本编辑框关闭事件
  mindMapInstance.value.on(
    "hide_text_edit",
    (textEditNode, activeNodeList, node) => {
      console.log(
        "节点文本编辑框关闭事件:",
        textEditNode,
        activeNodeList,
        node
      );
    }
  );

  // 节点树渲染完毕事件
  mindMapInstance.value.on("node_tree_render_end", () => {
    console.log("节点树渲染完毕");
  });

  // 画布的单击事件
  mindMapInstance.value.on("draw_click", () => {
    // 如果是节点点击触发的冒泡事件，则忽略
    if (isNodeClicked) {
      console.log("画布的单击事件 (由节点点击冒泡触发，已忽略)");
      return;
    }

    clearHighlight();
    // 隐藏右键菜单
    hideContextMenu();
  });
};

// 存储事件处理器的引用，以便后续清理
const keyboardEventHandlers = ref([]);
const globalEventHandlers = ref([]);

// 添加全局事件监听器
const _addGlobalEventListeners = () => {
  // 全局点击事件：点击空白处隐藏右键菜单
  const globalClickHandler = (e) => {
    // 检查点击是否在右键菜单内部
    if (contextMenu.value && contextMenu.value.contains(e.target)) {
      return; // 点击在菜单内部，不隐藏
    }

    // 检查点击是否在思维导图容器内部
    if (mindMapContainer.value && mindMapContainer.value.contains(e.target)) {
      return; // 点击在思维导图内部，由其他事件处理
    }

    // 点击在外部，隐藏菜单
    hideContextMenu();
  };

  // 添加事件监听器
  document.addEventListener("click", globalClickHandler, true);

  // 保存处理器引用以便清理
  globalEventHandlers.value.push({
    element: document,
    event: "click",
    handler: globalClickHandler,
  });
};

// 清理全局事件监听器
const _cleanupGlobalEventListeners = () => {
  globalEventHandlers.value.forEach(({ element, event, handler }) => {
    element.removeEventListener(event, handler, true);
  });
  globalEventHandlers.value = [];
};

// 彻底禁用所有键盘快捷键
const _disableAllKeyboardShortcuts = () => {
  if (!mindMapInstance.value) return;

  try {
    // 方法1: 尝试禁用keyCommand（如果存在的话）
    if (
      mindMapInstance.value.keyCommand &&
      typeof mindMapInstance.value.keyCommand.disable === "function"
    ) {
      mindMapInstance.value.keyCommand.disable();
    } else if (
      mindMapInstance.value.command &&
      typeof mindMapInstance.value.command.disableShortcuts === "function"
    ) {
      mindMapInstance.value.command.disableShortcuts();
    }

    // 通用的键盘事件阻止函数
    const preventKeyboard = (e) => {
      // 更全面的快捷键列表
      const isShortcut =
        e.key === "Delete" ||
        e.key === "Backspace" ||
        e.key === "Tab" ||
        e.key === "Enter" ||
        e.key === "Escape" ||
        e.key === "F2" ||
        e.key === "Insert" ||
        (e.ctrlKey && (e.key === "c" || e.key === "C")) ||
        (e.ctrlKey && (e.key === "v" || e.key === "V")) ||
        (e.ctrlKey && (e.key === "x" || e.key === "X")) ||
        (e.ctrlKey && (e.key === "z" || e.key === "Z")) ||
        (e.ctrlKey && (e.key === "y" || e.key === "Y")) ||
        (e.ctrlKey && (e.key === "a" || e.key === "A")) ||
        (e.ctrlKey && (e.key === "d" || e.key === "D")) ||
        (e.ctrlKey && (e.key === "s" || e.key === "S")) ||
        (e.ctrlKey && e.shiftKey && (e.key === "z" || e.key === "Z")) ||
        (e.altKey && e.key === "F4") ||
        // 方向键组合
        (e.ctrlKey &&
          ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(
            e.key
          )) ||
        (e.shiftKey &&
          ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(
            e.key
          )) ||
        // F功能键
        [
          "F1",
          "F2",
          "F3",
          "F4",
          "F5",
          "F6",
          "F7",
          "F8",
          "F9",
          "F10",
          "F11",
          "F12",
        ].includes(e.key) ||
        // 其他常见快捷键
        (e.key === " " && e.ctrlKey) || // Ctrl+Space
        e.key === "Home" ||
        e.key === "End" ||
        e.key === "PageUp" ||
        e.key === "PageDown";

      if (isShortcut) {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();

        const shortcutDesc =
          e.ctrlKey || e.altKey || e.shiftKey
            ? `${e.ctrlKey ? "Ctrl+" : ""}${e.altKey ? "Alt+" : ""}${
                e.shiftKey ? "Shift+" : ""
              }${e.key}`
            : e.key;
        return false;
      }
    };

    // 检查是否在思维导图区域内的函数
    const isInMindMapArea = () => {
      const activeElement = document.activeElement;
      const container = mindMapContainer.value;

      if (!container) return false;

      return (
        container.contains(activeElement) ||
        activeElement === container ||
        container.querySelector("svg") === activeElement ||
        activeElement?.closest(".mind-map-container") === container
      );
    };

    // 全局键盘事件处理器
    const globalKeyHandler = (e) => {
      if (isInMindMapArea()) {
        preventKeyboard(e);
      }
    };

    // 容器键盘事件处理器
    const containerKeyHandler = (e) => {
      preventKeyboard(e);
    };

    // 在思维导图容器上添加键盘事件拦截
    const container = mindMapContainer.value;
    if (container) {
      container.addEventListener("keydown", containerKeyHandler, true);
      container.addEventListener("keyup", containerKeyHandler, true);
      container.addEventListener("keypress", containerKeyHandler, true);

      // 确保容器可以接收键盘事件
      container.tabIndex = -1;

      // 保存处理器引用
      keyboardEventHandlers.value.push(
        { element: container, event: "keydown", handler: containerKeyHandler },
        { element: container, event: "keyup", handler: containerKeyHandler },
        { element: container, event: "keypress", handler: containerKeyHandler }
      );
    }

    // 在document级别添加全局拦截
    document.addEventListener("keydown", globalKeyHandler, true);
    document.addEventListener("keyup", globalKeyHandler, true);

    // 保存全局处理器引用
    keyboardEventHandlers.value.push(
      { element: document, event: "keydown", handler: globalKeyHandler },
      { element: document, event: "keyup", handler: globalKeyHandler }
    );
  } catch (error) {
    console.error("禁用键盘快捷键时出错:", error);
  }
};

// 清理键盘事件监听器
const _cleanupKeyboardEventListeners = () => {
  keyboardEventHandlers.value.forEach(({ element, event, handler }) => {
    element.removeEventListener(event, handler, true);
  });
  keyboardEventHandlers.value = [];
};

// 彻底禁用节点编辑功能
const _disableNodeEditing = () => {
  if (!mindMapInstance.value) return;

  try {
    // 方法1: 直接禁用textEdit实例
    if (mindMapInstance.value.renderer && mindMapInstance.value.renderer.textEdit) {
      const textEdit = mindMapInstance.value.renderer.textEdit;

      // 重写showEditTextBox方法使其无效
      textEdit.showEditTextBox = () => {
        console.log("节点编辑已被禁用");
        return false;
      };

      // 重写show方法使其无效
      textEdit.show = () => {
        console.log("节点编辑已被禁用");
        return false;
      };

      // 确保编辑框始终隐藏
      textEdit.hideEditTextBox && textEdit.hideEditTextBox();
    }

    // 方法2: 禁用相关配置
    if (mindMapInstance.value.opt) {
      mindMapInstance.value.opt.enableNodeTextEditOnDoubleClick = false;
    }

    // 方法3: 拦截所有可能的编辑触发方式
    const originalExecCommand = mindMapInstance.value.execCommand;
    mindMapInstance.value.execCommand = function(name, ...args) {
      // 阻止文本编辑相关的命令
      if (name === 'TEXT_EDIT' || name === 'START_TEXT_EDIT' || name === 'EDIT_NODE_TEXT') {
        console.log(`编辑命令 ${name} 已被禁用`);
        return false;
      }
      // 其他命令正常执行
      return originalExecCommand.call(this, name, ...args);
    };

    console.log("节点编辑功能已彻底禁用");
  } catch (error) {
    console.error("禁用节点编辑时出错:", error);
  }
};

// 初始化内部数据副本
const _initInternalData = (mindMapData) => {
  if (mindMapData && mindMapData.nodes && mindMapData.links) {
    internalMindMapData.value = {
      nodes: [...mindMapData.nodes],
      links: [...mindMapData.links],
    };
  }
};

// 转换网络图数据为思维导图数据格式
const _convertToMindMapData = (mindMapData) => {
  if (!mindMapData || !mindMapData.nodes || !mindMapData.links) {
    console.warn("思维导图数据不完整或为空");
    return null;
  }
  const { nodes, links } = mindMapData;

  // 创建节点映射
  const nodeMap = new Map();
  nodes.forEach((node) => {
    nodeMap.set(node.id, {
      ...node,
      uid: node.id,
      children: [],
    });
  });

  // 根据连接关系构建层次结构
  const childrenMap = new Map();
  links.forEach((link) => {
    if (!childrenMap.has(link.source)) {
      childrenMap.set(link.source, []);
    }
    childrenMap.get(link.source).push({
      targetId: link.target,
      label: link.label,
    });
  });

  // 递归构建思维导图结构
  const buildMindMapNode = (nodeId, visited = new Set()) => {
    if (visited.has(nodeId)) {
      // 避免循环引用，返回简化节点
      const node = nodeMap.get(nodeId);
      return {
        data: {
          uid: node.id,
          text: node.label,
          type: node.type, // 直接保存类型信息
          isExpand: true,
        },
      };
    }

    visited.add(nodeId);
    const node = nodeMap.get(nodeId);
    if (!node) return null;

    const mindMapNode = {
      data: {
        uid: node.id,
        text: node.label,
        type: node.type, // 直接保存类型信息
        isExpand: true,
      },
      children: [],
    };

    // 获取子节点
    const children = childrenMap.get(nodeId) || [];
    children.forEach((child) => {
      const childNode = buildMindMapNode(child.targetId, new Set(visited));
      if (childNode) {
        // 在子节点中添加关系信息
        childNode.data.relationLabel = child.label;
        mindMapNode.children.push(childNode);
      }
    });

    visited.delete(nodeId);
    return mindMapNode;
  };

  // 动态找到根节点（层次结构中最上层的节点）
  const findRootNode = () => {
    // 统计每个节点作为父节点的次数和深度
    const nodeStats = new Map();
    nodes.forEach((node) => {
      nodeStats.set(node.id, {
        asParent: 0,
        asChild: 0,
        level: 0,
      });
    });

    // 统计父子关系
    links.forEach((link) => {
      if (nodeStats.has(link.source)) {
        nodeStats.get(link.source).asParent++;
      }
      if (nodeStats.has(link.target)) {
        nodeStats.get(link.target).asChild++;
      }
    });

    // 找到最可能的根节点：
    // 1. 优先选择从未作为子节点的节点（没有父节点）
    // 2. 如果都有父节点，选择作为父节点次数最多的
    let rootCandidates = [];

    // 首先找没有父节点的节点
    for (const [nodeId, stats] of nodeStats) {
      if (stats.asChild === 0) {
        rootCandidates.push({ nodeId, stats });
      }
    }

    // 如果没有找到没有父节点的节点，选择作为父节点次数最多的
    if (rootCandidates.length === 0) {
      let maxAsParent = 0;
      for (const [nodeId, stats] of nodeStats) {
        if (stats.asParent > maxAsParent) {
          maxAsParent = stats.asParent;
          rootCandidates = [{ nodeId, stats }];
        } else if (stats.asParent === maxAsParent && stats.asParent > 0) {
          rootCandidates.push({ nodeId, stats });
        }
      }
    }

    // 如果还是没有合适的候选者，选择第一个节点
    if (rootCandidates.length === 0 && nodes.length > 0) {
      return nodes[0].id;
    }

    // 从候选者中选择第一个
    return rootCandidates.length > 0 ? rootCandidates[0].nodeId : null;
  };

  const rootNodeId = findRootNode();
  if (!rootNodeId) {
    console.warn("无法找到根节点");
    return null;
  }

  return buildMindMapNode(rootNodeId);
};

// 根据节点类型获取颜色
const _getNodeColor = (type) => {
  const colorMap = {
    核心领域: "#4A90E2",
    数学基础: "#7ED321",
    编程语言: "#F5A623",
    "具体技术/概念": "#BD10E0",
    应用领域: "#B8E986",
  };
  return colorMap[type] || "#50E3C2";
};

// 递归获取所有节点
const _getAllNodes = (node, nodes = []) => {
  if (!node) return nodes;

  nodes.push(node);
  if (node.children && node.children.length > 0) {
    node.children.forEach((child) => {
      _getAllNodes(child, nodes);
    });
  }
  return nodes;
};

// 性能优化：构建节点缓存
const _buildNodeCache = () => {
  if (!mindMapInstance.value) return nodeCache.value;

  const root = mindMapInstance.value.renderer?.root;
  if (!root) return nodeCache.value;

  const allNodes = _getAllNodes(root);
  const nodeMap = new Map();
  const nameMap = new Map();
  const typeMap = new Map();

  allNodes.forEach((node) => {
    const nodeId = node.uid;
    const nodeName = node.nodeData?.data?.text || "";
    const nodeType = node.nodeData?.data?.type || "";

    // 构建ID映射
    nodeMap.set(nodeId, node);

    // 构建名称映射
    if (nodeName) {
      if (!nameMap.has(nodeName)) {
        nameMap.set(nodeName, []);
      }
      nameMap.get(nodeName).push(node);
    }

    // 构建类型映射
    if (nodeType) {
      if (!typeMap.has(nodeType)) {
        typeMap.set(nodeType, []);
      }
      typeMap.get(nodeType).push(node);
    }
  });

  nodeCache.value = {
    allNodes,
    nodeMap,
    nameMap,
    typeMap,
  };

  return nodeCache.value;
};

// 通用节点查找方法
const _findNodesByCondition = (condition, collectChildren = false) => {
  const cache = _buildNodeCache();
  const targetNodes = [];
  const highlightNodeIds = new Set();

  // 根据条件查找节点
  if (condition.type === "id") {
    const nodeIds = Array.isArray(condition.value)
      ? condition.value
      : [condition.value];
    nodeIds.forEach((id) => {
      const node = cache.nodeMap.get(id);
      if (node) targetNodes.push(node);
    });
  } else if (condition.type === "name") {
    const nodeNames = Array.isArray(condition.value)
      ? condition.value
      : [condition.value];
    nodeNames.forEach((name) => {
      // 支持模糊匹配
      cache.nameMap.forEach((nodes, mapName) => {
        if (mapName.includes(name) || mapName === name) {
          targetNodes.push(...nodes);
        }
      });
    });
  } else if (condition.type === "type") {
    const nodeTypes = Array.isArray(condition.value)
      ? condition.value
      : [condition.value];
    nodeTypes.forEach((type) => {
      const nodes = cache.typeMap.get(type);
      if (nodes) targetNodes.push(...nodes);
    });
  }

  // 收集目标节点
  if (collectChildren) {
    // 递归收集目标节点及其所有子节点
    const collectNodeAndChildren = (node) => {
      highlightNodeIds.add(node.uid);
      if (node.children && node.children.length > 0) {
        node.children.forEach((child) => {
          collectNodeAndChildren(child);
        });
      }
    };

    targetNodes.forEach((targetNode) => {
      collectNodeAndChildren(targetNode);
    });
  } else {
    // 只收集目标节点本身
    targetNodes.forEach((node) => {
      highlightNodeIds.add(node.uid);
    });
  }

  return { targetNodes, highlightNodeIds, allNodes: cache.allNodes };
};

// 通用高亮应用方法
const _applyHighlight = (highlightNodeIds, allNodes) => {
  highlightedNodes.value = highlightNodeIds;

  // 应用样式 - 使用多种方式确保在只读模式下也能生效
  allNodes.forEach((node) => {
    const nodeElement = node.group?.node;
    if (nodeElement) {
      if (highlightNodeIds.has(node.uid)) {
        // 高亮节点 - 使用多种方式设置样式
        _setNodeHighlightStyle(nodeElement, true);
      } else {
        // 弱化其他节点
        _setNodeHighlightStyle(nodeElement, false);
      }
    }
  });
};

// 设置节点高亮样式的通用方法
const _setNodeHighlightStyle = (nodeElement, isHighlight) => {
  if (!nodeElement) return;

  if (isHighlight) {
    // 方法1: 添加CSS类
    nodeElement.classList.add("node-highlighted");
    nodeElement.classList.remove("node-dimmed");

    // 方法2: 直接设置内联样式作为备选方案
    const shapeElement = nodeElement.querySelector(".smm-node-shape");
    const textElement = nodeElement.querySelector(".smm-node-text");

    if (shapeElement) {
      shapeElement.style.transform = "scale(1.05)";
      shapeElement.style.boxShadow = "0 6px 20px rgba(255, 255, 255, 1)";
      shapeElement.style.stroke = "#fff";
      shapeElement.style.zIndex = "10";
    }

    if (textElement) {
      textElement.style.fontWeight = "700";
      textElement.style.color = "#2b6cb0";
    }

    // 方法3: 设置自定义属性用于识别
    nodeElement.setAttribute("data-highlight-state", "highlighted");
  } else {
    // 弱化节点
    nodeElement.classList.add("node-dimmed");
    nodeElement.classList.remove("node-highlighted");

    // 直接设置内联样式
    nodeElement.style.opacity = "0.3";

    const shapeElement = nodeElement.querySelector(".smm-node-shape");
    const textElement = nodeElement.querySelector(".smm-node-text");

    if (shapeElement) {
      shapeElement.style.filter = "grayscale(0.5)";
      shapeElement.style.transform = "scale(0.95)";
    }

    if (textElement) {
      textElement.style.color = "#a0aec0";
    }

    nodeElement.setAttribute("data-highlight-state", "dimmed");
  }
};

// ======= 数据更新和重渲染方法 =======

// 更新内部数据并重新渲染思维导图
const _updateMindMapData = () => {
  try {
    if (!mindMapInstance.value || !internalMindMapData.value) return;

    // 清空缓存
    _clearNodeCache();

    // 转换数据格式
    const convertedData = _convertToMindMapData(internalMindMapData.value);
    if (!convertedData) {
      console.error("数据转换失败");
      return;
    }

    // 更新思维导图数据
    mindMapInstance.value.setData(convertedData);

    // 重新渲染
    mindMapInstance.value.render();
  } catch (error) {
    console.error("更新思维导图数据时出错:", error);
  }
};

// 清空节点缓存
const _clearNodeCache = () => {
  nodeCache.value = {
    allNodes: [],
    nodeMap: new Map(),
    nameMap: new Map(),
    typeMap: new Map(),
  };
};

// 验证节点数据格式
const _validateNodeData = (node) => {
  if (!node || typeof node !== "object") {
    return { valid: false, error: "节点必须是一个对象" };
  }

  if (!node.id) {
    return { valid: false, error: "节点必须有id属性" };
  }

  if (!node.label) {
    return { valid: false, error: "节点必须有label属性" };
  }

  return { valid: true };
};

// 验证连接数据格式
const _validateLinkData = (link) => {
  if (!link || typeof link !== "object") {
    return { valid: false, error: "连接必须是一个对象" };
  }

  if (!link.source || !link.target) {
    return { valid: false, error: "连接必须有source和target属性" };
  }

  return { valid: true };
};

// ======= 节点管理API方法 =======

// API 方法：添加单个节点
const addNode = (nodeData, parentNodeId = null, linkData = {}) => {
  try {
    if (!mindMapInstance.value) {
      console.error("添加节点失败: 思维导图实例未初始化");
      return false;
    }

    // 验证节点数据
    const nodeValidation = _validateNodeData(nodeData);
    if (!nodeValidation.valid) {
      console.error("添加节点失败:", nodeValidation.error);
      return false;
    }

    if (parentNodeId) {
      // 查找父节点
      const parentNode =
        mindMapInstance.value.renderer.findNodeByUid(parentNodeId);
      if (!parentNode) {
        console.error("添加节点失败: 父节点不存在", parentNodeId);
        return false;
      }

      // 激活父节点
      mindMapInstance.value.renderer.activeNodeList = [parentNode];

      // 使用库原生API添加子节点
      mindMapInstance.value.execCommand("INSERT_CHILD_NODE", false, [], {
        uid: nodeData.id,
        text: nodeData.label,
        data: {
          type: nodeData.type || "默认类型",
          relationLabel: linkData.label || "",
          ...nodeData, // 支持其他自定义属性
        },
      });
    } else {
      // 如果没有指定父节点，添加为根节点的子节点
      const rootNode = mindMapInstance.value.renderer.root;
      if (rootNode) {
        mindMapInstance.value.renderer.activeNodeList = [rootNode];
        mindMapInstance.value.execCommand("INSERT_CHILD_NODE", false, [], {
          uid: nodeData.id,
          text: nodeData.label,
          data: {
            type: nodeData.type || "默认类型",
            ...nodeData,
          },
        });
      } else {
        console.error("添加节点失败: 无法找到根节点");
        return false;
      }
    }

    // 清空缓存以确保数据一致性
    _clearNodeCache();

    return true;
  } catch (error) {
    console.error("添加节点时出错:", error);
    return false;
  }
};

// API 方法：批量添加节点
const addNodes = (nodesData) => {
  try {
    if (!mindMapInstance.value) {
      console.error("批量添加节点失败: 思维导图实例未初始化");
      return false;
    }

    if (!Array.isArray(nodesData)) {
      console.error("添加节点失败: nodesData必须是数组");
      return false;
    }

    if (nodesData.length === 0) {
      console.warn("没有节点需要添加");
      return true;
    }

    // 预先验证所有节点数据
    for (const nodeConfig of nodesData) {
      const { nodeData } = nodeConfig;
      const nodeValidation = _validateNodeData(nodeData);
      if (!nodeValidation.valid) {
        console.error("批量添加节点失败:", nodeValidation.error, nodeData);
        return false;
      }
    }

    let successCount = 0;
    const failedNodes = [];

    // 逐个添加节点
    for (const nodeConfig of nodesData) {
      const { nodeData, parentNodeId = null, linkData = {} } = nodeConfig;

      try {
        if (parentNodeId) {
          // 查找父节点
          const parentNode =
            mindMapInstance.value.renderer.findNodeByUid(parentNodeId);
          if (!parentNode) {
            console.error(
              "跳过节点添加: 父节点不存在",
              parentNodeId,
              nodeData.id
            );
            failedNodes.push({ nodeData, reason: "父节点不存在" });
            continue;
          }

          // 激活父节点并添加子节点
          mindMapInstance.value.renderer.activeNodeList = [parentNode];
          mindMapInstance.value.execCommand("INSERT_CHILD_NODE", false, [], {
            uid: nodeData.id,
            text: nodeData.label,
            data: {
              type: nodeData.type || "默认类型",
              relationLabel: linkData.label || "",
              ...nodeData,
            },
          });
        } else {
          // 添加为根节点的子节点
          const rootNode = mindMapInstance.value.renderer.root;
          if (rootNode) {
            mindMapInstance.value.renderer.activeNodeList = [rootNode];
            mindMapInstance.value.execCommand("INSERT_CHILD_NODE", false, [], {
              uid: nodeData.id,
              text: nodeData.label,
              data: {
                type: nodeData.type || "默认类型",
                ...nodeData,
              },
            });
          } else {
            failedNodes.push({ nodeData, reason: "无法找到根节点" });
            continue;
          }
        }

        successCount++;
      } catch (error) {
        console.error("添加单个节点失败:", error, nodeData.id);
        failedNodes.push({ nodeData, reason: error.message });
      }
    }

    // 清空缓存以确保数据一致性
    _clearNodeCache();

    if (failedNodes.length > 0) {
      console.warn(
        `批量添加完成: 成功${successCount}个，失败${failedNodes.length}个`,
        failedNodes
      );
    }
    return failedNodes.length === 0;
  } catch (error) {
    console.error("批量添加节点时出错:", error);
    return false;
  }
};

// API 方法：删除单个或多个节点
const removeNode = (nodeIds, removeChildren = false) => {
  try {
    if (!mindMapInstance.value) {
      console.error("删除节点失败: 思维导图实例未初始化");
      return false;
    }

    // 统一处理单个ID或ID数组
    const targetNodeIds = Array.isArray(nodeIds) ? nodeIds : [nodeIds];

    if (targetNodeIds.length === 0 || targetNodeIds.some((id) => !id)) {
      console.error("删除节点失败: 节点ID不能为空");
      return false;
    }

    const nodesToDelete = [];
    const failedNodes = [];

    // 查找所有要删除的节点
    targetNodeIds.forEach((nodeId) => {
      const node = mindMapInstance.value.renderer.findNodeByUid(nodeId);
      if (node) {
        nodesToDelete.push(node);
      } else {
        failedNodes.push({ nodeId, reason: "节点不存在" });
      }
    });

    if (nodesToDelete.length === 0) {
      console.error("删除节点失败: 所有指定的节点都不存在");
      return false;
    }

    // 激活要删除的节点
    mindMapInstance.value.renderer.activeNodeList = nodesToDelete;

    // 使用库原生API删除节点
    if (removeChildren) {
      // 删除节点及其所有子节点
      mindMapInstance.value.execCommand("REMOVE_NODE");
    } else {
      // 只删除当前节点，保留子节点
      mindMapInstance.value.execCommand("REMOVE_CURRENT_NODE");
    }

    // 清空缓存以确保数据一致性
    _clearNodeCache();

    if (failedNodes.length > 0) {
      console.warn(
        `删除操作完成: 成功删除${nodesToDelete.length}个节点，${failedNodes.length}个节点未找到`,
        failedNodes
      );
    }

    return failedNodes.length === 0;
  } catch (error) {
    console.error("删除节点时出错:", error);
    return false;
  }
};

// API 方法：编辑单个节点
const editNode = (nodeId, updateData) => {
  try {
    if (!mindMapInstance.value) {
      console.error("编辑节点失败: 思维导图实例未初始化");
      return false;
    }

    if (!nodeId) {
      console.error("编辑节点失败: 节点ID不能为空");
      return false;
    }

    if (!updateData || typeof updateData !== "object") {
      console.error("编辑节点失败: 更新数据必须是一个对象");
      return false;
    }

    // 不允许修改节点ID
    if (Object.prototype.hasOwnProperty.call(updateData, "id")) {
      console.error("编辑节点失败: 不允许修改节点ID");
      return false;
    }

    // 查找节点实例
    const targetNode = mindMapInstance.value.renderer.findNodeByUid(nodeId);
    if (!targetNode) {
      console.error("编辑节点失败: 节点不存在", nodeId);
      return false;
    }

    // 验证label字段
    if (Object.prototype.hasOwnProperty.call(updateData, "label")) {
      if (!updateData.label || typeof updateData.label !== "string") {
        console.error("编辑节点失败: label必须是非空字符串");
        return false;
      }
    }

    // 激活节点
    mindMapInstance.value.renderer.activeNodeList = [targetNode];

    // 使用库原生API更新节点数据
    if (updateData.label) {
      // 修改节点文本
      targetNode.nodeData.data.text = updateData.label;
    }

    // 更新其他数据属性
    if (updateData.type) {
      targetNode.nodeData.data.type = updateData.type;
    }

    // 更新其他自定义属性
    Object.keys(updateData).forEach((key) => {
      if (key !== "label" && key !== "type" && key !== "id") {
        if (!targetNode.nodeData.data) {
          targetNode.nodeData.data = {};
        }
        targetNode.nodeData.data[key] = updateData[key];
      }
    });

    // 重新渲染节点
    targetNode.render();

    // 清空缓存以确保数据一致性
    _clearNodeCache();

    return true;
  } catch (error) {
    console.error("编辑节点时出错:", error);
    return false;
  }
};

// ======= 高亮API方法 =======

// API 方法：按照节点id高亮指定节点 (支持字符串或数组)
const highlightNodeByNodeId = (targetNodeIds) => {
  if (!mindMapInstance.value) return;

  // 清除之前的高亮
  clearHighlight();

  try {
    const result = _findNodesByCondition(
      { type: "id", value: targetNodeIds },
      false
    );

    if (result.targetNodes.length === 0) {
      console.warn("未找到目标节点:", targetNodeIds);
      return;
    }

    _applyHighlight(result.highlightNodeIds, result.allNodes);
  } catch (error) {
    console.error("按节点ID高亮时出错:", error);
  }
};

// API 方法：按照节点id高亮指定节点及其子节点(支持字符串或数组)
const highlightNodeAndChildrenByNodeId = (targetNodeIds) => {
  if (!mindMapInstance.value) return;

  // 清除之前的高亮
  clearHighlight();

  try {
    const result = _findNodesByCondition(
      { type: "id", value: targetNodeIds },
      true
    );

    if (result.targetNodes.length === 0) {
      console.warn("未找到目标节点:", targetNodeIds);
      return;
    }

    _applyHighlight(result.highlightNodeIds, result.allNodes);
  } catch (error) {
    console.error("按节点ID高亮节点及其子节点时出错:", error);
  }
};

// API 方法：按照节点名称高亮指定节点 (支持字符串或数组)
const highlightNodeByNodeName = (targetNodeNames) => {
  if (!mindMapInstance.value) return;

  // 清除之前的高亮
  clearHighlight();

  try {
    const result = _findNodesByCondition(
      { type: "name", value: targetNodeNames },
      false
    );

    if (result.targetNodes.length === 0) {
      console.warn("未找到目标节点:", targetNodeNames);
      return;
    }

    _applyHighlight(result.highlightNodeIds, result.allNodes);
  } catch (error) {
    console.error("按节点名称高亮时出错:", error);
  }
};

// API 方法：按照节点名称高亮指定节点及其子节点 (支持字符串或数组)
const highlightNodeAndChildrenByNodeName = (targetNodeNames) => {
  if (!mindMapInstance.value) return;

  // 清除之前的高亮
  clearHighlight();

  try {
    const result = _findNodesByCondition(
      { type: "name", value: targetNodeNames },
      true
    );

    if (result.targetNodes.length === 0) {
      console.warn("未找到目标节点:", targetNodeNames);
      return;
    }

    _applyHighlight(result.highlightNodeIds, result.allNodes);
  } catch (error) {
    console.error("按节点名称高亮节点及其子节点时出错:", error);
  }
};

// API 方法：按类型高亮节点(支持字符串或数组)
const highlightNodeByType = (targetType) => {
  if (!targetType || !mindMapInstance.value) return;

  // 清除之前的高亮
  clearHighlight();

  try {
    const result = _findNodesByCondition(
      { type: "type", value: targetType },
      false
    );

    if (result.targetNodes.length === 0) {
      console.warn("未找到目标类型的节点:", targetType);
      return;
    }

    _applyHighlight(result.highlightNodeIds, result.allNodes);
  } catch (error) {
    console.error("按类型高亮时出错:", error);
  }
};

// API 方法：按类型高亮节点及其子节点（支持字符串或数组）
const highlightNodeAndChildrenByType = (targetType) => {
  if (!targetType || !mindMapInstance.value) return;

  // 清除之前的高亮
  clearHighlight();

  try {
    const result = _findNodesByCondition(
      { type: "type", value: targetType },
      true
    );

    if (result.targetNodes.length === 0) {
      console.warn("未找到目标类型的节点:", targetType);
      return;
    }

    _applyHighlight(result.highlightNodeIds, result.allNodes);
  } catch (error) {
    console.error("按类型高亮节点及其子节点时出错:", error);
  }
};

// API 方法：清除高亮效果
const clearHighlight = () => {
  if (!mindMapInstance.value) return;

  try {
    const cache = _buildNodeCache();
    cache.allNodes.forEach((node) => {
      const nodeElement = node.group?.node;
      if (nodeElement) {
        // 清除CSS类
        nodeElement.classList.remove("node-highlighted");
        nodeElement.classList.remove("node-dimmed");

        // 清除内联样式
        _clearNodeInlineStyles(nodeElement);

        // 清除自定义属性
        nodeElement.removeAttribute("data-highlight-state");
      }
    });

    highlightedNodes.value.clear();
  } catch (error) {
    console.error("清除高亮时出错:", error);
  }
};

// 清除节点内联样式的辅助方法
const _clearNodeInlineStyles = (nodeElement) => {
  if (!nodeElement) return;

  // 清除节点容器的样式
  nodeElement.style.opacity = "";

  // 清除形状元素的样式
  const shapeElement = nodeElement.querySelector(".smm-node-shape");
  if (shapeElement) {
    shapeElement.style.transform = "";
    shapeElement.style.boxShadow = "";
    shapeElement.style.stroke = "";
    shapeElement.style.zIndex = "";
    shapeElement.style.filter = "";
  }

  // 清除文本元素的样式
  const textElement = nodeElement.querySelector(".smm-node-text");
  if (textElement) {
    textElement.style.fontWeight = "";
    textElement.style.color = "";
  }
};

// ======= 右键菜单功能 =======

// 显示右键菜单
const showContextMenu = (x, y, node) => {
  if (!node) {
    console.warn("无法显示菜单：节点为空");
    return;
  }

  currentRightClickNode.value = node;

  // 计算菜单位置
  const menuPosition = calculateMenuPosition(x, y);

  contextMenuStyle.value = {
    left: `${menuPosition.x}px`,
    top: `${menuPosition.y}px`,
  };

  contextMenuVisible.value = true;
};

// 隐藏右键菜单
const hideContextMenu = () => {
  contextMenuVisible.value = false;
  currentRightClickNode.value = null;
};

// 计算菜单位置，确保菜单不会超出视窗边界
const calculateMenuPosition = (x, y) => {
  const menuWidth = 180; // 菜单宽度
  const menuHeight = 200; // 菜单高度（大致估算）

  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;

  let adjustedX = x;
  let adjustedY = y;

  // 检查右边界
  if (x + menuWidth > viewportWidth) {
    adjustedX = viewportWidth - menuWidth - 10;
  }

  // 检查左边界
  if (adjustedX < 10) {
    adjustedX = 10;
  }

  // 检查下边界
  if (y + menuHeight > viewportHeight) {
    adjustedY = viewportHeight - menuHeight - 10;
  }

  // 检查上边界
  if (adjustedY < 10) {
    adjustedY = 10;
  }

  return { x: adjustedX, y: adjustedY };
};

// ======= 右键菜单操作函数 =======

// 插入同级节点
const insertSiblingNode = () => {
  if (!currentRightClickNode.value) {
    console.warn("无法插入同级节点：当前节点为空");
    return;
  }

  try {
    const currentNode = currentRightClickNode.value;

    // 激活当前节点
    mindMapInstance.value.renderer.activeNodeList = [currentNode];

    // 使用 INSERT_NODE 命令插入同级节点
    mindMapInstance.value.execCommand("INSERT_NODE", false);

    // 发送emit事件通知父组件
    emit("node-context-menu-action", {
      action: "insertSiblingNode",
      nodeId: currentNode.uid,
      nodeText: currentNode.nodeData?.data?.text || "",
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.error("插入同级节点时出错:", error);
    // 发送错误事件
    emit("node-context-menu-action", {
      action: "insertSiblingNode",
      nodeId: currentRightClickNode.value?.uid || null,
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  } finally {
    hideContextMenu();
  }
};

// 插入子级节点
const insertChildNode = () => {
  if (!currentRightClickNode.value) {
    console.warn("无法插入子级节点：当前节点为空");
    return;
  }

  try {
    const currentNode = currentRightClickNode.value;

    // 激活当前节点
    mindMapInstance.value.renderer.activeNodeList = [currentNode];

    // 使用 INSERT_CHILD_NODE 命令插入子级节点
    mindMapInstance.value.execCommand("INSERT_CHILD_NODE", false);

    // 发送emit事件通知父组件
    emit("node-context-menu-action", {
      action: "insertChildNode",
      nodeId: currentNode.uid,
      nodeText: currentNode.nodeData?.data?.text || "",
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.error("插入子级节点时出错:", error);
    // 发送错误事件
    emit("node-context-menu-action", {
      action: "insertChildNode",
      nodeId: currentRightClickNode.value?.uid || null,
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  } finally {
    hideContextMenu();
  }
};

// 插入父级节点
const insertParentNode = () => {
  if (!currentRightClickNode.value) {
    console.warn("无法插入父级节点：当前节点为空");
    return;
  }

  try {
    const currentNode = currentRightClickNode.value;

    // 激活当前节点
    mindMapInstance.value.renderer.activeNodeList = [currentNode];

    // 使用 INSERT_PARENT_NODE 命令插入父级节点
    mindMapInstance.value.execCommand("INSERT_PARENT_NODE", false);

    // 发送emit事件通知父组件
    emit("node-context-menu-action", {
      action: "insertParentNode",
      nodeId: currentNode.uid,
      nodeText: currentNode.nodeData?.data?.text || "",
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.error("插入父级节点时出错:", error);
    // 发送错误事件
    emit("node-context-menu-action", {
      action: "insertParentNode",
      nodeId: currentRightClickNode.value?.uid || null,
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  } finally {
    hideContextMenu();
  }
};

// 删除节点（包含子节点）
const deleteNodeWithChildren = () => {
  if (!currentRightClickNode.value) {
    console.warn("无法删除节点：当前节点为空");
    return;
  }

  try {
    const currentNode = currentRightClickNode.value;

    // 检查是否为根节点
    if (currentNode.isRoot) {
      console.warn("无法删除根节点");
      // 发送根节点删除限制事件
      emit("node-context-menu-action", {
        action: "deleteNodeWithChildren",
        nodeId: currentNode.uid,
        nodeText: currentNode.nodeData?.data?.text || "",
        warning: "无法删除根节点",
        timestamp: new Date().toISOString(),
      });
      return;
    }

    // 激活当前节点
    mindMapInstance.value.renderer.activeNodeList = [currentNode];

    // 使用 REMOVE_NODE 命令删除节点及其子节点
    mindMapInstance.value.execCommand("REMOVE_NODE");

    // 发送emit事件通知父组件
    emit("node-context-menu-action", {
      action: "deleteNodeWithChildren",
      nodeId: currentNode.uid,
      nodeText: currentNode.nodeData?.data?.text || "",
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.error("删除节点时出错:", error);
    // 发送错误事件
    emit("node-context-menu-action", {
      action: "deleteNodeWithChildren",
      nodeId: currentRightClickNode.value?.uid || null,
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  } finally {
    hideContextMenu();
  }
};

// 仅删除当前节点（保留子节点）
const deleteCurrentNodeOnly = () => {
  if (!currentRightClickNode.value) {
    console.warn("无法删除当前节点：当前节点为空");
    return;
  }

  try {
    const currentNode = currentRightClickNode.value;

    // 检查是否为根节点
    if (currentNode.isRoot) {
      console.warn("无法删除根节点");
      // 发送根节点删除限制事件
      emit("node-context-menu-action", {
        action: "deleteCurrentNodeOnly",
        nodeId: currentNode.uid,
        nodeText: currentNode.nodeData?.data?.text || "",
        warning: "无法删除根节点",
        timestamp: new Date().toISOString(),
      });
      return;
    }

    // 激活当前节点
    mindMapInstance.value.renderer.activeNodeList = [currentNode];

    // 使用 REMOVE_CURRENT_NODE 命令仅删除当前节点
    mindMapInstance.value.execCommand("REMOVE_CURRENT_NODE");

    // 发送emit事件通知父组件
    emit("node-context-menu-action", {
      action: "deleteCurrentNodeOnly",
      nodeId: currentNode.uid,
      nodeText: currentNode.nodeData?.data?.text || "",
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.error("删除当前节点时出错:", error);
    // 发送错误事件
    emit("node-context-menu-action", {
      action: "deleteCurrentNodeOnly",
      nodeId: currentRightClickNode.value?.uid || null,
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  } finally {
    hideContextMenu();
  }
};

// API 方法：按层级展示节点
const showByLevel = (level) => {
  if (!mindMapInstance.value) return;

  try {
    const root = mindMapInstance.value.renderer?.root;
    if (!root) {
      console.warn("根节点不可用");
      return;
    }

    if (level === "all") {
      // 全部展开
      mindMapInstance.value.command.exec("EXPAND_ALL");
      return;
    }

    const targetLevel = parseInt(level);
    if (isNaN(targetLevel)) return;

    mindMapInstance.value.execCommand("UNEXPAND_TO_LEVEL", targetLevel);
  } catch (error) {
    console.error("按层级展示时出错:", error);
  }
};

// 组件挂载
onMounted(async () => {
  // 等待下一个tick再初始化，确保props已经传入
  await nextTick();
  _initInternalData(props.mindMapData);
  _initMindMap(internalMindMapData.value);
});

// 监听数据变化
watch(
  () => props.mindMapData,
  (newData) => {
    if (newData) {
      // 更新内部数据副本
      _initInternalData(newData);

      // 清空缓存以确保数据一致性
      _clearNodeCache();

      // 如果思维导图已初始化，则重新渲染
      if (mindMapInstance.value) {
        const convertedData = _convertToMindMapData(internalMindMapData.value);
        if (convertedData) {
          mindMapInstance.value.setData(convertedData);
          mindMapInstance.value.render();
        }
      }
    }
  },
  { deep: true, immediate: true }
);

// 组件卸载时清理
onUnmounted(() => {
  // 清理键盘事件监听器
  _cleanupKeyboardEventListeners();

  // 清理全局事件监听器
  _cleanupGlobalEventListeners();

  // 销毁思维导图实例
  if (mindMapInstance.value) {
    try {
      mindMapInstance.value.destroy();
    } catch (error) {
      console.error("销毁思维导图实例时出错:", error);
    }
  }
});

// 对外暴露 API
defineExpose({
  // 节点管理功能
  addNode,
  addNodes,
  removeNode,
  editNode,
  // 获取当前数据
  getCurrentData: () => internalMindMapData.value,

  // 高亮功能
  highlightNodeByNodeId,
  highlightNodeAndChildrenByNodeId,
  highlightNodeByNodeName,
  highlightNodeAndChildrenByNodeName,
  highlightNodeByType,
  highlightNodeAndChildrenByType,
  clearHighlight,

  // 层级展示功能
  showByLevel,

  // 思维导图实例访问
  getMindMapInstance: () => mindMapInstance.value,
});
</script>

<style scoped lang="scss">
.mind-map-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  font-family: "Alibaba PuHuiTi", "Arial", sans-serif;
}

.mind-map-canvas {
  flex: 1;
  position: relative;
  overflow: hidden;
  border-radius: 0 0 12px 12px;
  background-color: rgb(207 216 231) !important;
}

// 自定义思维导图样式
:deep(.smm-node) {
  font-family: "Alibaba PuHuiTi", "Arial", sans-serif;

  // 根节点样式
  &.smm-node-root {
    .smm-node-shape {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }

  // 一级节点样式
  &.smm-node-generalization {
    .smm-node-shape {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }

  // 高亮节点样式
  &.node-highlighted {
    .smm-node-shape {
      transform: scale(1.05) !important;
      box-shadow: 0 6px 20px rgba(255, 255, 255, 1) !important;
      stroke: #fff !important;
      z-index: 10 !important;
    }

    .smm-node-text {
      font-weight: 700 !important;
      color: #2b6cb0 !important;
    }
  }

  // 弱化节点样式
  &.node-dimmed {
    opacity: 0.3 !important;

    .smm-node-shape {
      filter: grayscale(0.5) !important;
      transform: scale(0.95) !important;
    }

    .smm-node-text {
      color: #a0aec0 !important;
    }
  }
}

// 通过自定义属性进行高亮样式设置（只读模式的备选方案）
:deep(.smm-node[data-highlight-state="highlighted"]) {
  .smm-node-shape {
    transform: scale(1.05) !important;
    box-shadow: 0 6px 20px rgba(255, 255, 255, 1) !important;
    stroke: #fff !important;
    z-index: 10 !important;
  }

  .smm-node-text {
    font-weight: 700 !important;
    color: #2b6cb0 !important;
  }
}

:deep(.smm-node[data-highlight-state="dimmed"]) {
  opacity: 0.3 !important;

  .smm-node-shape {
    filter: grayscale(0.5) !important;
    transform: scale(0.95) !important;
  }

  .smm-node-text {
    color: #a0aec0 !important;
  }
}

// 强制隐藏所有可能的文本编辑框
:deep(.smm-text-edit),
:deep(.smm-text-edit-input),
:deep(.smm-text-edit-textarea),
:deep([class*="text-edit"]),
:deep([class*="textEdit"]) {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
}

// 右键菜单样式
.context-menu {
  position: fixed;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  z-index: 1000;
  min-width: 180px;
  padding: 8px 0;
  font-family: "Alibaba PuHuiTi", "Arial", sans-serif;
  user-select: none;

  .context-menu-item {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;
    background: none;
    width: 100%;
    text-align: left;
    font-size: 14px;
    color: #4a5568;

    &:hover {
      background-color: #f7fafc;
      color: #2d3748;
    }

    &.danger {
      color: #e53e3e;

      &:hover {
        background-color: #fed7d7;
        color: #c53030;
      }
    }

    .menu-icon {
      margin-right: 12px;
      font-size: 16px;
      width: 20px;
      text-align: center;
      flex-shrink: 0;
    }

    .menu-text {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .context-menu-divider {
    height: 1px;
    background-color: #e2e8f0;
    margin: 8px 0;
  }
}
</style>
